package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.bxscn;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.excel.ExcelTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.kafka.JFKafkaProducer;
import com.gzhryc.common.kafka.KafkaProducerFactory;
import com.gzhryc.common.kafka.models.KafkaMessage;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.DateBranchHelper;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.enums.EPayType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.base.models.OrderLogContent;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNShopOrder;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNShopOrderLog;
import com.gzhryc.shared_device.bxscn.code.dao.enums.BXSCNShopOrderEnum;
import com.gzhryc.shared_device.bxscn.code.dao.enums.EBXSCNCostMode;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNShopOrderLogService;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNShopOrderService;
import com.gzhryc.shared_device.bxscn.code.services.dto.BXSCNShopOrderSearch;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayOrder;
import com.gzhryc.shared_device.common.payment.dao.db.WXRefundOrder;
import com.gzhryc.shared_device.common.payment.services.WXPayOrderService;
import com.gzhryc.shared_device.common.payment.services.WXRefundOrderService;
import com.gzhryc.shared_device.oem.code.KafkaEventConstants;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.business.BXSCNShopBusinessEventListener;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.member.services.MemberBusinessOrderService;
import com.gzhryc.shared_device.oem.code.member.services.MemberCouponService;
import com.gzhryc.shared_device.oem.code.order.RedisCacheManager;
import com.gzhryc.shared_device.oem.code.order.event.OrderFinishEvent;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrder;
import com.gzhryc.shared_device.oem.code.profit.dao.enums.BusinessOrderEnum;
import com.gzhryc.shared_device.oem.code.profit.service.BusinessOrderService;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class BXSCNShopOrderController {

    static Logger log = Logger.getLogger(BXSCNShopOrderController.class);

    @Route("/bxscn/shop_order/list.html")
    public String list(HttpServletRequest request) {
        request.setAttribute("payStateList", BXSCNShopOrderEnum.PayState.values());
        request.setAttribute("stateList", BXSCNShopOrderEnum.State.values());
        request.setAttribute("dateBranchItemList", DateBranchHelper.self().getYearDateBranchItems());
        return "/bxscn/shop_order/list.html";
    }

    @Route(value = "/bxscn/shop_order/list.data")
    public ListResult<BXSCNShopOrder> listData(HttpServletRequest request,HttpSession session) {
        ListResult<BXSCNShopOrder> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        BXSCNShopOrderSearch search = WebUtils.getParameter(request, BXSCNShopOrderSearch.class);
        String searchDate = WebUtils.getString(request,"searchDate");
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            search.setLeaseAgentId(loginUser.getId());
            try {
                if (StringTools.isNotBlank(searchDate)) {
                    String[] strings = searchDate.split(" - ");
                    if (strings.length == 2) {
                        Date startDate = DateUtils.parseDate(strings[0], "yyyy-MM-dd");
                        Date endDate = DateUtils.parseDate(strings[1], "yyyy-MM-dd");
                        search.setStartDate(startDate);
                        search.setEndDate(endDate);
                    }
                }

                Date dateBranch = new Date();
                if(StringTools.isNotBlank(search.getDateBranchId())){
                    dateBranch = DateBranchHelper.getDateByItemId(search.getDateBranchId());
                }

                //缓存
                session.setAttribute("BXSCNShopOrderSearch",search);

                result.getBody().setTotal(BXSCNShopOrderService.self(dateBranch).countBySearch(search));
                List<BXSCNShopOrder> data = BXSCNShopOrderService.self(dateBranch).findBySearch(search, pageNo, pageLimit);
                if (data != null && data.size() > 0) {
                    result.setCode(DtoConstants.SUCCESS, null);
                    result.getBody().setData(data);
                }
            } catch (Exception e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route("/bxscn/shop_order/info.html")
    public String info(HttpServletRequest request) {
        String tradeNo = WebUtils.getString(request, "tradeNo");
        Date createDate = WebUtils.getDate(request, "createDate");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (StringTools.isNotBlank(tradeNo) && loginUser != null) {
            if (createDate == null) {
                createDate = new Date();
            }

            BXSCNShopOrder deviceOrder = BXSCNShopOrderService.self(createDate).getByTradeNo(tradeNo);
            if (deviceOrder != null && deviceOrder.getLeaseAgentId() != null && deviceOrder.getLeaseAgentId().equals(loginUser.getId())) {
                WebUtils.setAttribute(request, deviceOrder);
                if (EPayType.WXPay.index().equals(deviceOrder.getPayType())) {
                    WXPayOrder payOrder = WXPayOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getPayTradeNo());
                    if (payOrder != null) {
                        request.setAttribute("payOrder", payOrder);
                        List<WXRefundOrder> refundOrderList = WXRefundOrderService.self(deviceOrder.getCreateDate()).findByBusinessTradeNo(payOrder.getBusinessTradeNo());
                        request.setAttribute("refundOrderList", refundOrderList);
                    }
                }
            }
        }
        return "/bxscn/shop_order/info.html";
    }

    @Route(value = "/bxscn/shop_order/operate/record/list.data")
    public ListResult<OrderLogContent.LogItem> logListData(HttpServletRequest request) {
        ListResult<OrderLogContent.LogItem> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        String tradeNo = WebUtils.getString(request,"tradeNo");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if(StringTools.isNotBlank(tradeNo) && loginUser != null) {
            Date createDate = WebUtils.getDate(request, "createDate");
            if (createDate == null) {
                createDate = new Date();
            }

            BXSCNShopOrder deviceOrder = BXSCNShopOrderService.self(createDate).getByTradeNo(tradeNo);
            if (deviceOrder != null && deviceOrder.getLeaseAgentId() != null && deviceOrder.getLeaseAgentId().equals(loginUser.getId())) {
                BXSCNShopOrderLog orderLog = BXSCNShopOrderLogService.self(createDate).getByTradeNo(tradeNo);
                if (orderLog != null && StringTools.isNotBlank(orderLog.getContent())) {
                    OrderLogContent logContent = JsonTools.fromJson(orderLog.getContent(), OrderLogContent.class);
                    if (logContent != null) {
                        result.setCode(DtoConstants.SUCCESS, null);
                        result.getBody().setData(logContent.getItems());
                    }
                }
            }
        }
        return result;
    }

    @Route("/bxscn/shop_order/operate/lease.html")
    public String lease(HttpServletRequest request) {
        String tradeNo = WebUtils.getString(request,"tradeNo");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if(StringTools.isNotBlank(tradeNo) && loginUser != null) {
            Date createDate = WebUtils.getDate(request,"createDate");
            if(createDate == null){
                createDate = new Date();
            }

            BXSCNShopOrder deviceOrder = BXSCNShopOrderService.self(createDate).getByTradeNo(tradeNo);
            if (deviceOrder != null && deviceOrder.getLeaseAgentId() != null && deviceOrder.getLeaseAgentId().equals(loginUser.getId())) {
                WebUtils.setAttribute(request, deviceOrder);
            }
        }
        return "/bxscn/shop_order/lease.html";
    }

    @Route(value = {"/bxscn/shop_order/operate/lease.do"})
    public AjaxResult doLease(HttpServletRequest request, HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "租借完成失败");
        String tradeNo = WebUtils.getString(request, "tradeNo");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (StringTools.isNotBlank(tradeNo) && loginUser != null) {
            Date createDate = WebUtils.getDate(request, "createDate");
            String portableBatterySn = WebUtils.getString(request, "portableBatterySn");
            if (StringTools.isBlank(portableBatterySn)) {
                result.setMsg("请填写电池序列号");
                return result;
            }
            if (createDate == null) {
                createDate = new Date();
            }

            BXSCNShopOrder deviceOrder = BXSCNShopOrderService.self(createDate).getByTradeNo(tradeNo);
            if (deviceOrder != null && deviceOrder.getLeaseAgentId() != null && deviceOrder.getLeaseAgentId().equals(loginUser.getId())) {
                if (!BXSCNShopOrderEnum.State.WaitLease.index().equals(deviceOrder.getState())) {
                    result.setMsg("订单状态异常");
                    return result;
                }

                deviceOrder.setPortableBatterySn(portableBatterySn);

                OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                operateInfo.setOperator(EOperatorType.Agent.index(), loginUser.getFullName());

                BXSCNShopBusinessEventListener businessEventListener = new BXSCNShopBusinessEventListener();
                try {
                    if (BXSCNShopOrderService.self(deviceOrder.getCreateDate()).leaseFinish(deviceOrder, operateInfo, businessEventListener)) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    result.setMsg(e.getMessage());
                }
            }
        }
        return result;
    }

    @Route("/bxscn/shop_order/operate/revert.html")
    public String revert(HttpServletRequest request) {
        String tradeNo = WebUtils.getString(request,"tradeNo");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (StringTools.isNotBlank(tradeNo) && loginUser != null) {
            Date createDate = WebUtils.getDate(request, "createDate");
            if (createDate == null) {
                createDate = new Date();
            }

            BXSCNShopOrder deviceOrder = BXSCNShopOrderService.self(createDate).getByTradeNo(tradeNo);
            if (deviceOrder != null && deviceOrder.getLeaseAgentId() != null && deviceOrder.getLeaseAgentId().equals(loginUser.getId())) {
                WebUtils.setAttribute(request, deviceOrder);
            }
        }
        request.setAttribute("revertTypeList",BXSCNShopOrderEnum.RevertType.values());
        return "/bxscn/shop_order/revert.html";
    }

    @Route(value = {"/bxscn/shop_order/operate/revert.do"})
    public AjaxResult doRevert(HttpServletRequest request, HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "归还完成失败");
        String tradeNo = WebUtils.getString(request, "tradeNo");
        Long revertPlaceId = WebUtils.getLong(request, "revertPlaceId");
        Integer revertType = WebUtils.getInteger(request, "revertType");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (StringTools.isNotBlank(tradeNo) && revertPlaceId != null && loginUser != null) {
            Date createDate = WebUtils.getDate(request, "createDate");
            if (createDate == null) {
                createDate = new Date();
            }

            BXSCNShopOrder deviceOrder = BXSCNShopOrderService.self(createDate).getByTradeNo(tradeNo);
            if (deviceOrder != null && deviceOrder.getLeaseAgentId() != null && deviceOrder.getLeaseAgentId().equals(loginUser.getId())) {
                if (!BXSCNShopOrderEnum.State.Lease.index().equals(deviceOrder.getState())) {
                    result.setMsg("订单状态异常");
                    return result;
                }

                deviceOrder.setRevertType(revertType);

                if (deviceOrder.getRevertPlaceId() == null || !deviceOrder.getRevertPlaceId().equals(revertPlaceId)) {
                    PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(revertPlaceId);
                    if (physicalStore == null) {
                        result.setMsg("未找到归还的网点");
                        return result;
                    }

                    deviceOrder.setRevertPlaceId(physicalStore.getId());
                    deviceOrder.setRevertPlaceName(physicalStore.getName());
                    deviceOrder.setRevertProvince(physicalStore.getProvince());
                    deviceOrder.setRevertCity(physicalStore.getCity());
                    deviceOrder.setRevertCityArea(physicalStore.getCityArea());
                    deviceOrder.setRevertAreaCode(physicalStore.getAreaCode());
                    deviceOrder.setRevertAddress(physicalStore.getAddress());
                    deviceOrder.setRevertAgentId(physicalStore.getUserId());
                    deviceOrder.setRevertLatitude(physicalStore.getLatitude());
                    deviceOrder.setRevertLongitude(physicalStore.getLongitude());
                }

                OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                operateInfo.setOperator(EOperatorType.Agent.index(), loginUser.getFullName());

                try {
                    int finishResult = BXSCNShopOrderService.self(deviceOrder.getCreateDate()).revertFinish(deviceOrder, PayServiceFactory.self()
                            , MemberCouponService.self(), operateInfo);
                    if (finishResult > 0) {
                        if (finishResult == 2) {
                            deviceOrder = BXSCNShopOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(tradeNo);
                            //同步会员订单
                            if (!MemberBusinessOrderService.self(deviceOrder.getCreateDate()).finish(deviceOrder.getTradeNo(), deviceOrder.getMoney(), deviceOrder.getPayMoney()
                                    , deviceOrder.getWalletMoney(),operateInfo)) {
                                log.error("修改会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                            }
                            //触发订单完成
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OperateInfo temp = ClassTools.copy(new OperateInfo(), operateInfo);
                                OrderFinishEvent event = new OrderFinishEvent(EBusinessType.BXSCN_SHOP.index(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate(), temp);
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order, KafkaEventConstants.KEY_OrderFinish, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("未初始化消息队列，订单{{0}}未触发完成事件", deviceOrder.getTradeNo());
                            }
                        }
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    result.setMsg(e.getMessage());
                }
            } else {
                result.setCode(DtoConstants.NOT_POWER, "无权限操作");
            }
        }
        return result;
    }

    @Route(value = { "/bxscn/shop_order/operate/cancel.html" })
    public String cancel(HttpServletRequest request) {
        return "/bxscn/shop_order/cancel.html";
    }

    @Route(value = { "/bxscn/shop_order/operate/cancel.do" })
    public AjaxResult doCancel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "撤销失败");
        String tradeNo = WebUtils.getString(request, "tradeNo");
        String note = WebUtils.getString(request, "note");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (StringTools.isNotBlank(tradeNo) && loginUser != null) {
            if (StringTools.isBlank(note)) {
                result.setMsg("请填撤销的原因");
                return result;
            }
            Date createDate = WebUtils.getDate(request, "createDate");
            if (createDate == null) {
                createDate = new Date();
            }


            try {
                BXSCNShopOrder deviceOrder = BXSCNShopOrderService.self(createDate).getByTradeNo(tradeNo);
                if (deviceOrder == null) {
                    result.setMsg("未找到租借订单");
                    return result;
                }

                if (deviceOrder.getLeaseAgentId() != null && deviceOrder.getLeaseAgentId().equals(loginUser.getId())) {
                    //检查分成
                    BusinessOrder businessOrder = BusinessOrderService.self(createDate).getByTradeNo(tradeNo);
                    if (businessOrder != null && (BusinessOrderEnum.DivideState.Finish.index().equals(businessOrder.getDivideState())
                            || BusinessOrderEnum.DivideState.CancelExecuting.index().equals(businessOrder.getDivideState()))) {
                        result.setMsg("订单已分成，请回滚分成后操作");
                        return result;
                    }

                    OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                    operateInfo.setOperator(EOperatorType.Agent.index(), loginUser.getFullName());
                    operateInfo.setOperateNote(note);

                    Date cancelDate = new Date();

                    int cancelResult = BXSCNShopOrderService.self(deviceOrder.getCreateDate()).cancel(deviceOrder, PayServiceFactory.self(), operateInfo);
                    if (cancelResult > 0) {
                        //清理缓存，避免定时器重复处理
                        RedisCacheManager.removeWorkingCDCZDeviceOrder(deviceOrder.getTradeNo());
                        if (cancelResult == 2) {
                            deviceOrder = BXSCNShopOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(tradeNo);
                            //同步会员订单
                            MemberBusinessOrderService.self(deviceOrder.getCreateDate()).cancel(deviceOrder.getTradeNo(), deviceOrder.getMoney()
                                    , deviceOrder.getPayMoney(), deviceOrder.getWalletMoney());
                            BusinessOrderService.self(deviceOrder.getCreateDate()).cancel(deviceOrder.getTradeNo(), cancelDate);
                        }
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                } else {
                    result.setCode(DtoConstants.NOT_POWER, "无权限操作");
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route("/bxscn/shop_order/operate/refund.html")
    public String refund(HttpServletRequest request) {
        String tradeNo = WebUtils.getString(request,"tradeNo");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (StringTools.isNotBlank(tradeNo) && loginUser != null) {
            Date createDate = WebUtils.getDate(request, "createDate");
            if (createDate == null) {
                createDate = new Date();
            }
            BXSCNShopOrder deviceOrder = BXSCNShopOrderService.self(createDate).getByTradeNo(tradeNo);
            if (deviceOrder != null && deviceOrder.getLeaseAgentId() != null && deviceOrder.getLeaseAgentId().equals(loginUser.getId())) {
                request.setAttribute("refundMoneyStr", deviceOrder.getPayMoneyStr());
            }
        }
        return "/bxscn/shop_order/refund.html";
    }

    @Route(value = {"/bxscn/shop_order/operate/refund.do"})
    public AjaxResult doRefund(HttpServletRequest request, HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "撤销订单失败");
        String tradeNo = WebUtils.getString(request, "tradeNo");
        Double refundMoneyStr = WebUtils.getDouble(request, "refundMoneyStr");
        String refundNote = WebUtils.getString(request, "refundNote");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (StringTools.isNotBlank(tradeNo) && loginUser != null) {
            if (refundMoneyStr == null) {
                result.setMsg("请填写退款金额");
                return result;
            }
            if (StringTools.isBlank(refundNote)) {
                result.setMsg("请填写退款原因");
                return result;
            }
            Date createDate = WebUtils.getDate(request, "createDate");
            if (createDate == null) {
                createDate = new Date();
            }


            try {
                BXSCNShopOrder deviceOrder = BXSCNShopOrderService.self(createDate).getByTradeNo(tradeNo);
                if (deviceOrder == null) {
                    result.setMsg("未找到租借订单");
                    return result;
                }

                if (deviceOrder.getLeaseAgentId() != null && deviceOrder.getLeaseAgentId().equals(loginUser.getId())) {
                    //检查分成
                    BusinessOrder businessOrder = BusinessOrderService.self(createDate).getByTradeNo(tradeNo);
                    if (businessOrder != null && (BusinessOrderEnum.DivideState.Finish.index().equals(businessOrder.getDivideState())
                            || BusinessOrderEnum.DivideState.CancelExecuting.index().equals(businessOrder.getDivideState()))) {
                        result.setMsg("订单已分成，请回滚分成后操作");
                        return result;
                    }

                    OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                    operateInfo.setOperator(EOperatorType.Agent.index(), loginUser.getFullName());
                    operateInfo.setOperateNote(refundNote);

                    Integer refundMoney = NumberTools.changeMoney(refundMoneyStr);

                    int refundResult = BXSCNShopOrderService.self(deviceOrder.getCreateDate()).refund(deviceOrder, refundMoney, PayServiceFactory.self(), operateInfo);
                    if (refundResult > 0) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                } else {
                    result.setCode(DtoConstants.NOT_POWER, "无权限操作");
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = "/bxscn/shop_order/excel/export.do")
    public void doExportExcel(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            String[] titles = {"设备序列号", "电池类型", "电池序列号", "租借类型", "租借网点ID", "租借网点名称", "租借网点地区", "归还类型"
                    , "归还网点ID", "归还网点名称", "归还网点地区", "会员ID", "会员名称", "会员手机号", "收费方式", "租借起始时间", "租借结束时间"
                    , "租借时长", "订单金额", "支付类型", "支付状态", "支付时间", "订单状态", "订单完成时间", "订单创建时间"};
            List<Object[]> data = new ArrayList<>();
            BXSCNShopOrderSearch search = WebUtils.getAttribute(session, "BXSCNShopOrderSearch", BXSCNShopOrderSearch.class);
            if (search == null) {
                search = new BXSCNShopOrderSearch();
            }
            Integer pageNo = 1;
            Integer pageLimit = WebConstants.PAGE_LIMIT;
            try {
                search.setLeaseAgentId(loginUser.getId());
                Date dateBranch = new Date();
                if (StringTools.isNotBlank(search.getDateBranchId())) {
                    dateBranch = DateBranchHelper.getDateByItemId(search.getDateBranchId());
                }
                List<BXSCNShopOrder> shopOrderList = BXSCNShopOrderService.self(dateBranch).findBySearch(search, pageNo, pageLimit);
                while (shopOrderList != null && shopOrderList.size() > 0) {
                    for (BXSCNShopOrder shopOrder : shopOrderList) {
                        Object[] objects = new Object[titles.length];
                        objects[0] = shopOrder.getTradeNo();
                        objects[1] = shopOrder.getBatteryTypeName();
                        objects[2] = shopOrder.getPortableBatterySn();
                        objects[3] = shopOrder.getLeaseTypeName();
                        objects[4] = shopOrder.getLeasePlaceId();
                        objects[5] = shopOrder.getLeasePlaceName();
                        objects[6] = shopOrder.getPlaceAreaName();
                        objects[7] = shopOrder.getRevertTypeName();
                        objects[8] = shopOrder.getRevertPlaceId();
                        objects[9] = shopOrder.getRevertPlaceName();
                        objects[10] = shopOrder.getRevertAreaName();
                        objects[11] = shopOrder.getMemberId();
                        objects[12] = shopOrder.getMemberName();
                        objects[13] = shopOrder.getMemberPhone();
                        objects[14] = EBXSCNCostMode.Deposit.note();
                        if (shopOrder.getStartDate() != null) {
                            objects[15] = DateFormatUtils.format(shopOrder.getStartDate(), "yyyy-MM-dd HH:mm:ss");
                        } else {
                            objects[15] = "";
                        }
                        if (shopOrder.getEndDate() != null) {
                            objects[16] = DateFormatUtils.format(shopOrder.getEndDate(), "yyyy-MM-dd HH:mm:ss");
                        } else {
                            objects[16] = "";
                        }
                        objects[17] = shopOrder.getLeaseDay();
                        objects[18] = shopOrder.getMoneyStr();
                        objects[19] = shopOrder.getPayTypeName();
                        objects[20] = shopOrder.getPayStateName();
                        if (shopOrder.getPayDate() != null) {
                            objects[21] = DateFormatUtils.format(shopOrder.getPayDate(), "yyyy-MM-dd HH:mm:ss");
                        } else {
                            objects[21] = "";
                        }
                        objects[22] = shopOrder.getStateName();
                        if (shopOrder.getFinishDate() != null) {
                            objects[23] = DateFormatUtils.format(shopOrder.getFinishDate(), "yyyy-MM-dd HH:mm:ss");
                        } else {
                            objects[23] = "";
                        }
                        if (shopOrder.getCreateDate() != null) {
                            objects[24] = DateFormatUtils.format(shopOrder.getCreateDate(), "yyyy-MM-dd HH:mm:ss");
                        } else {
                            objects[24] = "";
                        }
                        data.add(objects);
                    }
                    pageNo = pageNo + 1;
                    shopOrderList = BXSCNShopOrderService.self(dateBranch).findBySearch(search, pageNo, pageLimit);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            String name = format.format(new Date());
            WebUtils.exportExcel(response, name);
            ExcelTools.export(response.getOutputStream(), "电池(门店)租借订单信息", null, titles, data);
        }
    }
}
